<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同编号" prop="vBillNo">
        <el-input
          v-model="queryParams.vBillNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目号" prop="vProjectNo">
        <el-input
          v-model="queryParams.vProjectNo"
          placeholder="请输入项目号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="vProjectDec">
        <el-input
          v-model="queryParams.vProjectDec"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applyBy">
        <el-input
          v-model="queryParams.applyBy"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="billList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        label="序号"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="合同编号"
        align="center"
        prop="vBillNo"
        width="80px"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="toDetail(scope.row)">
            {{ scope.row.vBillNo }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="项目号"
        align="center"
        prop="vProjectNo"
        width="120px"
      />
      <el-table-column label="项目名称" align="center" prop="vProjectDec" />

      <el-table-column
        label="申请人"
        align="center"
        prop="applyBy"
        width="80px"
      />

      <el-table-column label="备注" align="center" prop="remark" width="80px" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listBill,
  getBill,
  delBill,
  addBill,
  updateBill,
  getInvoiceInfo,
  delInvoice,
  saveInvoice,
} from "@/api/buy/buy0003";
import { getToken } from "@/utils/auth";

export default {
  name: "Bill",
  dicts: ["sys_normal_disable", "spa_spa_kind"],
  data() {
    return {
      // 遮罩层
      loading: true,
      insertFlag: false,
      invoiceOpen: false,
      // 选中数组
      ids: [],
      vBillNos: [],
      vProjectNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vBillNo: null,
        status: "0",
        vProjectNo: null,
        vProjectDec: null,
        applyBy: null,
        oprBy: null,
        supplier: null,
        nAmt: null,
        nDays: null,
      },
      // 表单参数
      form: {
        id: null,
        vBillNo: null,
        status: null,
        vProjectNo: null,
        vProjectDec: null,
        delFlag: null,
        applyBy: null,
        oprBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        supplier: null,
        nAmt: null,
        nDays: null,
      },
      // 表单校验
      rules: {
        nAmt: [
          { required: true, trigger: "blur", message: "合同金额不能为空" },
        ],
        nDays: [{ required: true, trigger: "blur", message: "质保期不能为空" }],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/buy/buy0003/importData",
      },
      itemList: [],
      invoiceList: [],
      clickInvoiceRow: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams).then((response) => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vBillNo: null,
        status: null,
        vProjectNo: null,
        vProjectDec: null,
        delFlag: null,
        applyBy: null,
        oprBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        supplier: null,
        nAmt: null,
        nDays: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.vBillNos = selection.map((item) => item.vBillNo);
      this.vProjectNos = selection.map((item) => item.vProjectNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购合同";
      this.insertFlag = false;
    },
    toDetail(row) {
      let params = row;

      this.$router.push({
        name: "buy0004detail",
        params: params,
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBill(id).then((response) => {
        this.form = response.data.billPO;
        this.itemList = response.data.itemPOList;
        this.open = true;
        this.title = "修改采购合同";
      });
      this.insertFlag = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBill(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill({ billPO: this.form, itemPOList: this.itemList }).then(
              (response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            );
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该条数据项？")
        .then(function () {
          return delBill(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "buy/buy0003/export",
        {
          ...this.queryParams,
        },
        `bill_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "零件明细导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "buy/buy0003/importTemplate",
        {},
        `合同明细_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log("--------------------------------");
      console.log(response);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 发票信息按钮操作 */
    handleInvoice(row) {
      this.clickInvoiceRow = row;
      getInvoiceInfo({ nMainId: row.id, status: 0, delFlag: 0 }).then(
        (response) => {
          this.invoiceList = response.data;
          this.invoiceOpen = true;
        }
      );
    },
    //新增发票信息
    handleInvoiceAdd() {
      var _this = this;
      let list = {
        vInvoiceNo: "",
        status: 0,
        delFlag: "0",
      };

      _this.invoiceList.push(list);
    },

    /** 删除发票按钮操作 */
    handleInvDelete(index, row) {
      debugger;
      var _this = this;
      this.$modal
        .confirm("是否确认删除该条数据项？")
        .then(function () {
          debugger;
          if (
            row.id === "" ||
            row.id === null ||
            row.id === undefined ||
            row.id === 0
          ) {
          } else {
            return delInvoice(row);
          }
        })
        .then(() => {
          _this.invoiceList.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 删除发票按钮操作 */
    submitInvoice() {
      saveInvoice({
        billPO: this.clickInvoiceRow,
        invoiceList: this.invoiceList,
      }).then((response) => {
        this.invoiceOpen = false;
        this.getList();
      });
    },
    cancelInvoice() {
      this.invoiceOpen = false;
    },
    handleClose() {
      this.open = false;
      this.getList();
    },
    linkToPost() {
      let params = {
        ids: this.ids,
        vBillNos: this.vBillNos,
        vProjectNos: this.vProjectNos,
      };

      this.$router.push({
        name: "post",
        params: params,
      });
    },

    linkToPostRow(row) {
      let params = {
        ids: [row.id],
        vBillNos: [row.vBillNo],
        vProjectNos: [row.vProjectNo],
      };
      console.log("$$$$$$$$$$$$");
      console.log(params);
      this.$router.push({
        name: "post",
        params: params,
      });
    },
  },
};
</script>
